<template>
  <base-modal :title="title" :show.sync="visible" width="600px" class="base-import-modal">
    <span class="base-import-title" slot="title">
      {{title}}
      <el-tooltip v-if="tooltip"  placement="bottom" popper-class="batch-tooltip">
        <div slot="content" v-html="content"></div>
        <i class="iconfont icon-question"></i>
      </el-tooltip>
    </span>
    <slot name="tip">    
      <div class="base-import-warn">
        <i18n path="common.base.importModal.downloadTemplateTip" tag="span">
          <a place="link" :href="templateUrl">{{$t('common.base.importModal.importTemplate')}}</a>
        </i18n>
      </div>
    </slot>

    <div class="base-import-file">
      <p>{{fileName}}</p>
      <el-button type="primary" @click="choose" :disabled="pending">{{$t('common.base.chooseFile')}}</el-button>
      <input 
        type="file" 
        ref="file" 
        @change="change"
        :accept="accept"
      />
    </div>

    <div class="base-import-error" v-if="errors.length > 0">
      <h5>{{$t('common.base.importModal.tips1')}}</h5>
      <p v-for="(err, index) in errors" :key="index">{{err}}</p>
    </div>

    <div slot="footer" class="import-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="pending" @click="upload" :loading="pending">{{pending ? this.$t('common.base.importing') : this.$t('common.base.import')}}</el-button>
    </div>

  </base-modal>
</template>

<script>

import BaseModal from '../BaseModal';
import Uploader from '@src/util/uploader';
import Platform from '@src/platform';
import i18n from '@src/locales';

/* export & import */
import { importCellPhone } from '@src/api/Import';
/* util */
import { exportAlert } from '@src/util/alert';

export default {
  name: 'base-import',
  props: {
    templateUrl: String,
    // 是否立即 导入 或 异步导入显示在 导入导出列表
    isImportNow: {
      type: Boolean,
      default: false,
    }, 
    action: String,
    title: {
      type: String,
      default: i18n.t('common.base.import')
    },
    tooltip:{
      type:Boolean,
      default:false
    },
    content:{
      type:String,
      default:''
    },
    accept: {
      type: String,
      default: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    },
    uploadParamString: {
      type: String,
      default: ''
    },
    module: {
      type: String,
      default: ''
    },
    uploadParamObject: {
      type: Object,
      default:()=>( {} )
    },
  },
  data(){
    return {
      fileName: '',
      visible: false,
      pending: false,
      file: null,
      errors: []
    }
  },
  methods: {
    open(){
      this.pending = false;
      this.file = null;
      this.fileName = '';
      this.errors = [];

      this.visible = true;
    },
    choose(){
      this.$refs.file.value = null;
      this.$refs.file.click();
    },
    change(event){
      const files = event.target.files;
      if (!files || files.length == 0) return;
      let file = files[0];

      this.errors = [];
      this.fileName = file.name;
      this.file = file
    },
    upload(){
      if(null == this.file || !(this.file instanceof File)) return Platform.alert(this.$t('common.base.importModal.tips2'));

      this.pending = true;
      Uploader.upload(this.file, this.action, {
        validateStorage: false,
        uploadParamString: this.uploadParamString,
        module: this.module,
        ...this.uploadParamObject
      }).then(result => {

        if(result.status == 0){
          if(this.isImportNow) {
            let message = this.$t('common.base.importModal.tips4');
            // 导入联系人的时候，返回的total竟然统计了第一行表头
            let total = result.data.total;
            if (this.action === '/contacts/import' || this.action == importCellPhone) {
              total -= 1;
            }

            if(result.data && result.data.total) message += `${this.$t('common.base.importModal.tips3', {data1:total})}`;

            Platform.alert(message);
            this.visible = false;
            this.$emit('success', result);

          } else {
            this.visible = false;
            if(result.data && Array.isArray(result.data)){
              
              const message = result.data.join('\n');
              
              exportAlert(message)
              
            }else{
              
              const message = result.message;
              
              exportAlert(message);
              
            }
            
          }

        }else{
          if(this.isImportNow) {
            let data = result.data || [];
            this.errors = data;
          } else {
            Platform.alert(result.message);
          }
        }

        this.pending = false;
      })
        .catch(err => {
          console.error(err)
        })
    }
  },
  components: {
    [BaseModal.name]: BaseModal,
  }
}
</script>


<style lang="scss">
  .base-import-modal {

    .base-modal-header {
      justify-content: space-between;
    }
    .base-modal-body {
      padding: 15px;
    }
    .base-modal-footer {
      .import-footer {
        display: flex;
        justify-content: flex-end;
      }

    }
  }

.base-import-title{
  display: inline-block;
  min-width: 80px;
  margin-right: 10px;
  line-height: 20px;
  font-size: 16px;
  color: #303133;

  i{
    color:$text-color-secondary;
  }
}

.base-import-warn{
  padding: 5px 10px;
  border-radius: 2px;
  background-color: #fdf6ec;
  color: #e6a23c;
  margin-bottom: 15px;
  a {
    color: $color-primary;
  }
}


.base-import-file{
  display: flex;
  flex-flow: row nowrap;
  margin-bottom: 15px;

  &:last-child{
    margin-bottom: 5px;
  }
  p {
    flex: 1;
    line-height: 24px;
    padding: 3px 6px;
    border: 1px solid #d5d5d5;
    border-right: none;
    margin: 0;
    border-radius: 4px 0 0 4px;
  }

  .el-button{
    border-radius: 0 2px 2px 0;
  }

  input[type='file']{
    display: none;
  }
}

.base-import-error{
  max-height: 400px;
  overflow: auto;
  h5{
    font-size: 15px;
    margin: 0;
    line-height: 30px;
    font-weight: 500;
    color: red;
  }

  p{
    margin: 0;
    line-height: 24px;
    word-break: break-all;
  }
}

</style>
